package com.forum.article.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.forum.article.entity.ForumArticle;
import com.forum.article.entity.ForumArticleTag;
import com.forum.article.entity.ForumArticleTagMap;
import com.forum.article.mapper.ForumArticleMapper;
import com.forum.article.mapper.ForumArticleTagMapMapper;
import com.forum.article.mapper.ForumArticleTypeMapper;
import com.forum.article.service.ForumArticleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.forum.article.service.ForumArticleTagMapService;
import com.forum.article.service.ForumArticleTagService;
import com.forum.article.service.ForumArticleTypeService;
import com.forum.article.vo.ForumArticleVO;
import com.forum.article.vo.Result;
import com.forum.article.vo.TagVO;
import com.forum.article.vo.TypeVO;
import com.forum.article.vo.param.ArticleParam;
import com.forum.article.vo.param.PageParams;
import com.forum.common.utils.PageUtils;
import com.forum.common.utils.R;
import com.sun.xml.internal.bind.v2.runtime.reflect.opt.FieldAccessor_Boolean;
import com.sun.xml.internal.ws.policy.EffectiveAlternativeSelector;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.security.auth.callback.LanguageCallback;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author bncgnc
 * @since 2022-01-04
 */
@Service
public class ForumArticleServiceImpl extends ServiceImpl<ForumArticleMapper, ForumArticle> implements ForumArticleService {
    @Autowired
    ForumArticleMapper forumArticleMapper;
    @Autowired
    ForumArticleTagMapMapper forumArticleTagMapMapper;
    @Autowired
    ForumArticleTagMapService forumArticleTagMapService;
    @Autowired
    ForumArticleTagService forumArticleTagService;

    /**
     * 通过文章标签 文章类型 查找对应的文章
     * @param pageParams
     * @return
     */
    @Override
    public R articleByTypeAndTag(PageParams pageParams){
        Long articleTagId = pageParams.getArticleTagId();
        Long articleTypeId = pageParams.getArticleTypeId();

        List<ForumArticle> articlesByTag = null;
        List<ForumArticle> articlesByType = null;

        // 通过文章类型id查询对应文章
        if ( articleTypeId != null ) {
            articlesByType = forumArticleMapper.selectList(new QueryWrapper<ForumArticle>()
                    .eq("article_type_id", articleTypeId));
        }
        // 通过标签文章中间表查询文章
        if ( articleTagId != null ) {
            articlesByTag = forumArticleTagMapService.findForumArticleByTagId(articleTagId);
        }

        articlesByTag.addAll(articlesByType);
//        IPage<ForumArticle> forumArticleIPage = forumArticleMapper.listForumArticle(
//                page,
//                pageParams.getArticleTypeId(),
//                pageParams.getArticleTagId()
//            );
//        List<ForumArticle> records = forumArticleIPage.getRecords();
        return R.ok().put("success" , true).put("data" , PageUtils.getPages(pageParams.getCurrentPage() , pageParams.getPageSize() , articlesByTag));
    }


//    public Result listForumArticle(PageParams pageParams){
//        Page<ForumArticle> page = new Page<>(pageParams.getPaga(),pageParams.getPageSive());
//        LambdaQueryWrapper<ForumArticle> queryWrapper = new LambdaQueryWrapper<>();
//        根据创建时间倒序排列
//        queryWrapper.orderByDesc(ForumArticle::getCreateTime);
//        Page<ForumArticle> forumArticlePage = forumArticleMapper.selectPage(page, queryWrapper);
//        List<ForumArticle> records = forumArticlePage.getRecords();
//        不能直接返回
//        List<ForumArticleVO> forumArticleVOList = copyList(records);
//        return Result.success(forumArticleVOList);
//    }

    @Override
    public R hotForumArticle(int limit) {
//        LambdaQueryWrapper<ForumArticle> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.orderByDesc(ForumArticle::getArticleViews);
//        queryWrapper.select(ForumArticle::getId,ForumArticle::getArticleTitle);
//        queryWrapper.last("limit "+limit );
//        List<ForumArticle> forumArticles = forumArticleMapper.selectList(queryWrapper);
        QueryWrapper<ForumArticle> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("article_views" , "article_likes");
        wrapper.last("limit " + limit);

//        forumArticles.forEach(System.out::println);
        List<ForumArticle> forumArticles = forumArticleMapper.selectList(wrapper);

        return R.ok().put("success" , true).put("data" , forumArticles);
    }


    @Override
    public R newForumArticle(int limit) {
//        LambdaQueryWrapper<ForumArticle> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.orderByDesc(ForumArticle::getCreateTime);
//        queryWrapper.select(ForumArticle::getId,ForumArticle::getArticleTitle);
//        queryWrapper.last("limit "+limit);
//        List<ForumArticle> forumArticles = forumArticleMapper.selectList(queryWrapper);

        QueryWrapper<ForumArticle> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("create_time");
        wrapper.last("limit " + limit);

        List<ForumArticle> articles = forumArticleMapper.selectList(wrapper);

        return R.ok().put("success" , true).put("data" , articles);
    }


    @Override
    public Result findForumArticleById(Long articleId) {
        //根据id查询文章信息
        return null;
    }


    /**
     * 发布文章
     * @param articleParam
     * @return
     */
    @Override
    public R publish(ArticleParam articleParam) {
        ForumArticle forumArticle = new ForumArticle();
        // 设置作者id
        forumArticle.setUserId(articleParam.getId());

        forumArticle.setArticleViews(0);
        forumArticle.setArticleTitle(articleParam.getArticleTitle());
        forumArticle.setArticleDescription(articleParam.getArticleDescription());
        forumArticle.setArticleLikes(0);

        // 设置文章类型
        TypeVO type = articleParam.getType();
        forumArticle.setArticleTypeId(type.getId());


        forumArticle.setArticleContent(articleParam.getArticleContent());
        forumArticle.setArticleContentHtml(articleParam.getArticleContentHtml());



        this.forumArticleMapper.insert(forumArticle);

        //tag
        List<TagVO> tags = articleParam.getTags();
        if (tags != null && tags.size() > 0){
            for (TagVO tag : tags){
                Long forumArticleId = forumArticle.getId();
                ForumArticleTagMap forumArticleTagMap = new ForumArticleTagMap();
                forumArticleTagMap.setArticleTagId(tag.getId());
                forumArticleTagMap.setArticleId(forumArticleId);
                forumArticleTagMapMapper.insert(forumArticleTagMap);
            }
        }

//        Map<String,String> map = new HashMap<>();
//        map.put("id",forumArticle.getId().toString());

        return R.ok().put("success" ,true).put("id" , forumArticle.getId());
    }




    private List<ForumArticleVO> copyList(List<ForumArticle> records){
        List<ForumArticleVO> forumArticleVOList = new ArrayList<>();
        for (ForumArticle record:records){
            forumArticleVOList.add(copy(record));
        }
        return forumArticleVOList;
    }

    @Autowired
    ForumArticleTypeService forumArticleTypeService;

    private ForumArticleVO copy(ForumArticle forumArticle){
        ForumArticleVO forumArticleVO = new ForumArticleVO();
        forumArticle.setId(Long.valueOf(forumArticle.getId()));
        BeanUtils.copyProperties(forumArticle,forumArticleVO);

        Long articleId = forumArticle.getId();
        forumArticleVO.setTags(forumArticleTagService.findTagsByArticleId(articleId));

        Long typeId = forumArticle.getArticleTypeId();
        forumArticleVO.setType(forumArticleTypeService.findTypeById(typeId));


        return forumArticleVO;
    }

}

